//#include "../stdafx.h"
#include "utility/crc32.h"
#include "file/crc_md5.h"
#include "utility/assert.h"
#include <boost/crc.hpp>  
#include <exception>  
#include <fstream>     
#include "win.h"

namespace KCore{

	std::streamsize const buffer_size = 1024;

	bool crc32::crc_file(const char* file, unsigned long& crc)
	{
		boost::crc_32_type result;
		try
		{
			std::ifstream ifs(file, std::ios_base::binary);
			if ( ifs )
			{
				do
				{
					char buffer[buffer_size];
					ifs.read(buffer, buffer_size);
					result.process_bytes(buffer, ifs.gcount());
				} while (ifs);
			}
		}
		catch ( ... )
		{
			return false;
		}
		crc = result.checksum();
		return true;
	}


	unsigned long crc32::crc_str(const char* string)
	{
		boost::crc_32_type result;
		while(*string != '\0')
		{
			result.process_byte(*string);
			string++;
		}
		return result.checksum();
	}

	unsigned long crc32::crc_buffer(const char* string, size_t size)
	{
		boost::crc_32_type result;
		while(size--)
		{
			result.process_byte(*string);
			string++;
		}
		return result.checksum();
	}


	#ifdef __LINUX
	unsigned long StringCrc32(const char* szString)
	{
		return crc32::crc_str(szString);
	}	
	#else
	__declspec(dllexport) unsigned long StringCrc32(const char* szString)
	{
		return crc32::crc_str(szString);
	}
	#endif
	
	unsigned long crc_file(const char *file)
	{
		unsigned long crc;
		bool rt = crc32::crc_file(file, crc);
		if (rt)
			return crc;
		assert_comment1(rt == true,"crc wrong",file);
		return 0;
	}

	unsigned long crc_str(const char *string)
	{
		return StringCrc32(string);
	}

	unsigned long crc_buffer(const char *string,size_t size)
	{
		return crc32::crc_buffer(string, size);
	}
}
